package com.xunwulian.base.util;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {
    // 默认编码
    private static String CharSet = "utf8";

    // 换行
    private static String Br = "\r\n";

    // 头部名字
    private static String ClientIP = "Client-IP";
    private static String ContentEncoding = "Content-Encoding";
    private static String ContentLength = "Content-Length";
    private static String ContentType = "Content-Type";


    /**
     * map 转 参数
     *
     * @param paramMap 参数map
     * @param charset  参数编码
     * @return 字串参数
     * @throws UnsupportedEncodingException
     */
    public static String mapToParams(Map<String, String> paramMap, String charset) throws UnsupportedEncodingException {
        if (paramMap == null) {
            return new String();
        }

        StringBuilder params = new StringBuilder();
        for (String key : paramMap.keySet()) {
            String value = paramMap.get(key);
            key = URLEncoder.encode(key, charset);
            value = URLEncoder.encode(value, charset);
            params.append(key + "=" + value + "&");
        }

        if (StringUtils.isNoneBlank(params)) {
            params.deleteCharAt(params.length() - 1);
        }

        return params.toString();
    }

    /**
     * 参数 转 map
     *
     * @param params  字串参数
     * @param charset 参数编码
     * @return map参数
     * @throws UnsupportedEncodingException
     */
    public static Map<String, String> paramsToMap(String params, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(params)) {
            return new HashMap();
        }

        Map<String, String> map = new HashMap();
        String[] params2 = params.split("&");
        for (String param : params2) {
            String key = param.split("=")[0];
            key = URLDecoder.decode(key, charset);
            String value = param.split("=")[1];
            value = URLDecoder.decode(value, charset);
            map.put(key, value);
        }

        return map;
    }

    /**
     * 获取本地的IP地址
     *
     * @return IP地址
     */
    public static String localIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }
}
